package com.qiang.controller;

import com.qiang.enums.ExceptionCode;
import com.qiang.exception.ResultException;
import com.qiang.service.UserService;
import com.qiang.util.ExcutorUtil;
import com.qiang.util.HttpClient;
import com.qiang.util.ResultEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.WebAsyncTask;

import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName UserContriller
 * @Author zhuhongqiang
 * @Date 2019/4/1 10:31
 */

@RestController
@RequestMapping("user")
public class UserController extends BaseController{
    @Autowired
    UserService userService;




    /**
     * 获取用户
     * @param id
     * @return
     */
    @RequestMapping("getUser")
    public ResultEntity version(@RequestParam(value = "id") Integer id){
        return new ResultEntity(userService.getUserById(id));
    }


    /**
     * 测试异步调用超时返回
     * @return
     */
    @RequestMapping("/asyncTask")
    public WebAsyncTask<Object> uploadVoucherFile() {
        Callable<Object> callable = () -> {
            try {
                TimeUnit.SECONDS.sleep(7L);
                return  buildResponseEntity("success1");
            } catch (Exception e) {
                e.printStackTrace();
                return  buildResponseEntity("UPLOAD_RESULT_ERROR");
            }
        };
        //上传APP最多等待时间 5s
        WebAsyncTask asyncTask = new WebAsyncTask(5000, callable);
        asyncTask.onTimeout(() -> {
            throw new ResultException(ExceptionCode.TIME_OUT);
        });
        return asyncTask;
    }

    public static void main1(String[] args) throws InterruptedException {

        /**
         * resource：资源名，即限流规则的作用对象
         * limitApp：流控针对的调用来源，若为 default 则不区分调用来源
         * grade：限流阈值类型（QPS 或并发线程数）；0代表根据并发数量来限流，1代表根据QPS来进行流量控制
         * count：限流阈值
         * strategy：调用关系限流策略
         * controlBehavior：流量控制效果（直接拒绝、Warm Up、匀速排队）
         * clusterMode：是否为集群模式
         */
        while (true){
            TimeUnit.MILLISECONDS.sleep(150);
            ExcutorUtil.execute(() -> {
                int number = new Random().nextInt(10);
                String s = HttpClient.doGet("http://localhost:9090/down?name="+number+"&ok=hello:");
                System.out.println("s_down==="+s);
                s = HttpClient.doGet("http://localhost:9090/hello?name="+number+"&ok=hello:");
                System.out.println("s_hello==="+s);

//                String s1 = HttpClient.doGet("http://localhost:9090/hello?name="+number);
//                if (StringUtils.isNoneBlank(s1)){
//                    System.out.println("s1==="+s1);
//                }
            });

        }

    }

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            int finalI = i;
            ExecutorService executorService = Executors.newFixedThreadPool(50);
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(1);
                }
            });
        }
    }
}
